package cn.iocoder.yudao.module.erp.service.contract;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.erp.controller.admin.contract.vo.ContractPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.contract.vo.ContractRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.contract.vo.ContractSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.contractpaymentplan.vo.ContractPaymentPlanRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contract.ContractDO;
import cn.iocoder.yudao.module.erp.dal.mysql.contract.ErpContractMapper;
import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO;
import cn.iocoder.yudao.module.erp.service.contractfilerelation.ContractFileRelationService;
import cn.iocoder.yudao.module.erp.service.contractpaymentplan.ContractPaymentPlanService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.CONTRACT_NOT_EXISTS;

/**
 * 合同信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ErpContractMapper erpContractMapper;
    @Autowired
    private ContractFileRelationService contractFileRelationService;
    @Autowired
    private ContractPaymentPlanService contractPaymentPlanService;
    @Resource
    private ErpNoRedisDAO noRedisDAO;
    @Resource
    private BpmProcessInstanceApi processInstanceApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeptApi deptApi;


    @Value("${task.purchase_contract.key:purchase_contract}")
    private String purchaseContract;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createContract(ContractSaveReqVO createReqVO) {
        // 创建合同编号
        String no = noRedisDAO.generate(ErpNoRedisDAO.CONTRACT_NO_PREFIX);
        if (erpContractMapper.selectByNo(no) != null) {
            throw exception(CONTRACT_NOT_EXISTS);
        }
        createReqVO.setContractNo(no);
        if(StringUtils.isEmpty(createReqVO.getContractDepartment())){
            createReqVO.setContractDepartment(deptApi.getDept(createReqVO.getContractDepartmentId()).getName());
        }
        if(StringUtils.isEmpty(createReqVO.getContractResponsiblePerson())){
            createReqVO.setContractResponsiblePerson(adminUserApi.getUser(createReqVO.getContractResponsiblePersonId()).getNickname());
        }
        // 插入
        ContractDO contract = BeanUtils.toBean(createReqVO, ContractDO.class);
        erpContractMapper.insert(contract);

        //插入工作流
        Map<String, Object> processInstanceVariables = new HashMap<>();
        processInstanceVariables.put("purchaseContract", contract.getId());
        processInstanceVariables.put("purchaseContractNo", contract.getContractNo());
        processInstanceVariables.put("purchaseContractPartA", contract.getPartyA());
        processInstanceVariables.put("purchaseContractPartB", contract.getPartyB());
        processInstanceVariables.put("purchaseContractName", contract.getContractName());
        processInstanceVariables.put("purchaseContractAmountInclTax", contract.getContractAmountInclTax());
        String processInstanceId = processInstanceApi.createProcessInstance(getLoginUserId(),
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(purchaseContract)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(contract.getId()))
        );
        ContractDO update = new ContractDO();
        update.setId(contract.getId());
        update.setProcessInstanceId(processInstanceId);
        erpContractMapper.updateById(update);

        // 返回
        return contract.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateContract(ContractSaveReqVO updateReqVO) {
        // 校验存在
        validateContractExists(updateReqVO.getId());
        if(updateReqVO.getContractDepartmentId() != null && StringUtils.isEmpty(updateReqVO.getContractDepartment())){
            updateReqVO.setContractDepartment(deptApi.getDept(updateReqVO.getContractDepartmentId()).getName());
        }
        if(updateReqVO.getContractResponsiblePersonId() != null &&  StringUtils.isEmpty(updateReqVO.getContractResponsiblePerson())){
            updateReqVO.setContractResponsiblePerson(adminUserApi.getUser(updateReqVO.getContractResponsiblePersonId()).getNickname());
        }
        //
        // 更新
        ContractDO updateObj = BeanUtils.toBean(updateReqVO, ContractDO.class);
        erpContractMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteContract(Long id) {
        // 校验存在
        validateContractExists(id);
        // 删除
        erpContractMapper.deleteById(id);
        // 删除关联文件
        contractFileRelationService.deleteByContractId(id);
        // 删除付款计划
        contractPaymentPlanService.deleteByContractId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteContractListByIds(List<Long> ids) {
        // 校验存在
        validateContractExists(ids);
        // 删除
        erpContractMapper.deleteByIds(ids);
        // 删除关联文件
        contractFileRelationService.deleteByContractIds(ids);
        // 删除付款计划
        contractPaymentPlanService.deleteByContractIds(ids);
    }

    private void validateContractExists(List<Long> ids) {
        List<ContractDO> list = erpContractMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(CONTRACT_NOT_EXISTS);
        }
    }

    private void validateContractExists(Long id) {
        if (erpContractMapper.selectById(id) == null) {
            throw exception(CONTRACT_NOT_EXISTS);
        }
    }

    @Override
    public ContractRespVO getContract(Long id) {
        ContractDO contractDO = erpContractMapper.selectById(id);
        ContractRespVO respVO = BeanUtils.toBean(contractDO, ContractRespVO.class);
        //返回付款计划
        ContractPaymentPlanRespVO paymentPlanRespVO = contractPaymentPlanService.getByContractId(id);
        respVO.setPaymentPlanRespVO(paymentPlanRespVO);
        return respVO;
    }

    @Override
    public PageResult<ContractDO> getContractPage(ContractPageReqVO pageReqVO) {
        return erpContractMapper.selectPage(pageReqVO);
    }

    private void validatePurchaseContractExists(Long id) {
        if (erpContractMapper.selectById(id) == null) {
            throw exception(CONTRACT_NOT_EXISTS);
        }
    }


    @Override
    public int updateStatus(long id, Integer status) {
        validatePurchaseContractExists(id);
        ContractDO contractDO = new ContractDO();
        contractDO.setId(id);
        contractDO.setStatus(status);
        return erpContractMapper.updateById(contractDO);
    }

}